package club.kingyin.kyblog.core.utils.serialization;

import java.io.*;

/**
 * @author : kingyins
 * @version : 1.0
 * @program : Ky-Blog
 * @description : 在此处添加类描述
 * @create : 2021年08月16日 10:57
 **/
public class SerializationUtil {

    // 异常应该抛出给日志监测到
    public static String serializeAsString(Object obj) {
        return ByteUtil.encoder(serializeAsByteArray(obj));
    }

    public static byte[] serializeAsByteArray(Object obj) {
        if (null == obj) {
            return null;
        }
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
            out.writeObject(obj);
            return byteArrayOutputStream.toByteArray();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 反序列化
     *
     * @param bytes 对象序列化后的字节数组
     * @return 反序列化后的对象
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static Object deserialize(byte[] bytes) {
        if (null == bytes) {
            return null;
        }
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream in = new ObjectInputStream(byteArrayInputStream);
            return in.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 反序列化成指定类型的对象
     *
     * @param bytes 对象序列化后的字节数组
     * @param c 反序列化后的对象类型
     * @return 指定类型的对象
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static <T> T deserialize(byte[] bytes, Class<T> c) {
        return c.cast(deserialize(bytes));
    }

    public static Object deserialize(String resource) {
        return deserialize(ByteUtil.decoder(resource));
    }

    public static <T> T deserialize(String resource, Class<T> c) {
        return c.cast(deserialize(ByteUtil.decoder(resource)));
    }

}

